package com.dinree.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import com.alibaba.fastjson.TypeReference;
import com.base.library.TopBarBaseActivity;
import com.base.library.utils.JsonUtils;
import com.base.library.utils.StringUtils;
import com.dinree.R;
import com.dinree.api.UserApi;
import com.dinree.bean.SMSError;
import com.dinree.databinding.ActivityForgetBinding;
import com.jakewharton.rxbinding2.view.RxView;

import java.util.concurrent.TimeUnit;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

import static com.base.library.Constant.WINDOW_DURATION;

public class ForgetPwdActivity extends TopBarBaseActivity {
    private String phone;
    private String pwd;
    private String code;
    private ActivityForgetBinding activityForgetBinding;
    private EventHandler eventHandler;

    @Override
    public int getContentView() {
        return R.layout.activity_forget;
    }


    @Override
    public void initContentView(Bundle savedInstanceState) {
        phone = getIntent().getStringExtra("phone");
        activityForgetBinding = getContentViewBinding();
        setTitle("忘记密码");
        setTopLeftButton(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        SMSSDK.setAskPermisionOnReadContact(true);
        eventHandler = new EventHandler() {
            public void afterEvent(int event, int result, Object data) {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        submit();
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        showMsg("验证码已发送");
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                } else {
                    if (data instanceof Throwable) {
                        Throwable t = (Throwable) data;
                        String json = t.getMessage();
                        SMSError smsError = JsonUtils.getInstance().fromJson(json, new TypeReference<SMSError>() {
                        });
                        showMsg(smsError.detail);
                    } else {
                        showMsg("验证码错误");
                    }
                }
            }
        };

        // 注册监听器
        SMSSDK.registerEventHandler(eventHandler);
        RxView.clicks(activityForgetBinding.btnSubmit).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            submit();
//            Intent intent = new Intent(mContext, AuthenticationActivity.class);
//            startActivity(intent);
        });
        RxView.clicks(activityForgetBinding.btnCode).throttleFirst(WINDOW_DURATION, TimeUnit.SECONDS).subscribe(v -> {
            getCode();
        });
    }

    private void submit() {
        phone = activityForgetBinding.editPhone.getText().toString().trim();
        code = activityForgetBinding.editCode.getText().toString().trim();
        pwd = activityForgetBinding.editPwd.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            showMsg("手机号不能为空");
            return;
        }
        if (!StringUtils.isMainMobile(phone)) {
            showMsg("手机号码不正确");
            return;
        }
        if (StringUtils.isEmpty(code)) {
            showMsg("验证码不能为空");
            return;
        }
        if (StringUtils.isEmpty(pwd)) {
            showMsg("密码不能为空");
            return;
        }
        UserApi.getInstance(mContext).register("2", phone, pwd, code).subscribe(user -> {
            finish();
        }, e -> {
            e.printStackTrace();
            showMsg(e.getMessage());
        });
    }

    private void getCode() {
        phone = activityForgetBinding.editPhone.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            showMsg("手机号不能为空");
            return;
        }
        if (!StringUtils.isMainMobile(phone)) {
            showMsg("手机号码不正确");
            return;
        }
        final long count = 59;
        SMSSDK.getVerificationCode("+86", phone);
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(count + 1)
                .map(aLong -> count - aLong)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> {
                    activityForgetBinding.btnCode.setEnabled(false);
                    activityForgetBinding.btnCode.setTextColor(Color.BLACK);
                })
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long aLong) {
                        activityForgetBinding.btnCode.setText(String.format(getString(R.string.get_identifying_code_time), aLong));
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        activityForgetBinding.btnCode.setEnabled(true);
                        activityForgetBinding.btnCode.setTextColor(Color.WHITE);
                        activityForgetBinding.btnCode.setText(R.string.get_identifying_code);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}

